﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.BizFacade.Services;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered
{
    public static class CmsPageSiteMapExtensions
    {
        public static CmsPageSiteMap SiteMap(this HtmlHelper htmlHelper, object htmlAttributes = null)
        {
            return new CmsPageSiteMap(htmlHelper).Attributes(htmlAttributes);
        }
    }
    
    public class CmsPageSiteMap : CmsMvcBaseComponent<CmsPageSiteMap, IEnumerable<CmsPage>>
    {
        private readonly CmsPageService _pageService = new CmsPageService();

        protected override IEnumerable<CmsPage> Value
        {
            get
            {
                IEnumerable<CmsPage> data = null;
                
                var rootPage = _pageService.RootPage;

                if (rootPage != null)
                {
                    data = _pageService.GetChildPages(rootPage.Id, true).Where(p => p.IsVisible);
                }
                else
                {
                    data = new List<CmsPage>();
                }

                base.Value = data;

                return data;
            }
        }
        
        public CmsPageSiteMap(HtmlHelper htmlHelper)
            : base(htmlHelper)
        {
            Component = this;
        }
    }
}
